from flask import g
from flask_restplus import Resource, Namespace, fields, marshal

from app.coupon.model import CouponCode
from app.user.decorators import token_required, permission_required
from app.coupon.service import verify_code
from app.user.controller import simple_user_model
from app.coupon import dao
from common.responses import created, ok
from common.decorators import catch_error
from common.utils import custom_marshal_pagination
from common.request_parser import get_parser as base_get_parser

api = Namespace('coupon', path='/coupon')

# model
coupon_model = api.model('coupon_model', {
    'id': fields.String(description='id'),
    'code': fields.String(description='兑换码'),
    'is_sale': fields.Boolean(description='是否已发放'),
    'is_used': fields.Boolean(description='是否已兑换'),
    'coins': fields.Float(description='面值'),
    'consumer_user_id': fields.String(description='兑换者id'),
    'consumer_user': fields.Nested(simple_user_model),
    'update_datetime': fields.DateTime(description='更新时间')
})

verify_coupon_parser = api.parser()
verify_coupon_parser.add_argument('coupon_code', type=str, required=True, help='兑换码')


class VerifyCouponResource(Resource):
    @catch_error
    @token_required
    @api.expect(verify_coupon_parser)
    def post(self):
        args = verify_coupon_parser.parse_args()
        verify_code(
            company_id=g.company_id,
            user_id=g.user_id,
            code=args.get('coupon_code')
        )
        return ok(data={}, message='兑换券使用成功')


# ---------- get parser ----------

get_coupons_parser = base_get_parser.copy()
get_coupons_parser.add_argument('is_sale', type=str, choices=['true', 'false'], help='是否已发放')
get_coupons_parser.add_argument('is_used', type=str, choices=['true', 'false'], help='是否已兑换')
get_coupons_parser.add_argument('coins', type=int, help='面值')


class CouponsResource(Resource):
    @catch_error
    @token_required
    @api.expect(get_coupons_parser)
    def get(self):
        args = get_coupons_parser.parse_args()
        coupon_pagination = dao.get_by_page(
            company_id=g.company_id,
            page_size=args.get('per_page'),
            page=args.get('current_page'),
            sorted_by=args.get('sorted_by'),
            sorted_by_type=args.get('sorted_by_type'),

            search_str=args.get('search_str'),
            is_sale=args.get('is_sale'),
            is_used=args.get('is_used'),
            coins=args.get('coins')
        )
        coupon_pagination = custom_marshal_pagination(coupon_pagination)
        # 为每个元素添加内容
        new_items = []
        for ele in coupon_pagination['items']:
            record = CouponCode.query.filter_by(id=ele["id"]).first()
            new_items.append(record)
        coupon_pagination['items'] = marshal(new_items, coupon_model)
        return ok(data=coupon_pagination, message='Get records success')


put_coupon_parser = api.parser()
put_coupon_parser.add_argument('is_sale', type=bool, help='是否已发放')


class CouponResource(Resource):
    @catch_error
    @token_required
    @api.expect(put_coupon_parser)
    def put(self, coupon_id):
        args = put_coupon_parser.parse_args()
        coupon = CouponCode.query.filter_by(id=coupon_id).first()
        coupon.update(
            commit=True,
            is_sale=args.get('is_sale')
        )
        return ok(data=marshal(coupon, coupon_model), message="update success")


# --------- route ----------
# 消费兑换券
api.add_resource(VerifyCouponResource, '/verify_coupon')
api.add_resource(CouponsResource, '/coupons')
# 修改为已发放
api.add_resource(CouponResource, '/coupons/<int:obj_id>')
